package io.api.modules.project.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.admin.common.page.PageData;
import io.admin.common.service.impl.CrudServiceImpl;
import io.api.enums.Msg;
import io.api.enums.MsgType;
import io.api.enums.ProjectRole;
import io.api.modules.login.dto.WorkOrderDTO;
import io.api.modules.login.entity.UserEntity;
import io.api.modules.project.dao.MessageDao;
import io.api.modules.project.dto.MessageDTO;
import io.api.modules.project.entity.MessageEntity;
import io.api.modules.project.service.MessageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户消息表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-07-17
 */
@Service
public class MessageServiceImpl extends CrudServiceImpl<MessageDao, MessageEntity, MessageDTO> implements MessageService {

    @Override
    public QueryWrapper<MessageEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        Long userId = (Long)params.get("userId");
//        String isRead = (String)params.get("isRead");

        QueryWrapper<MessageEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);
//        wrapper.eq(StrUtil.isNotBlank(isRead), "is_read", Integer.parseInt(isRead));
        wrapper.eq("user_id", userId);
        wrapper.orderByAsc("type");
        wrapper.orderByAsc("is_read");
        wrapper.orderByAsc("msg_type");
        wrapper.orderByDesc("create_date");
        return wrapper;
    }


    @Transactional
    @Override
    public void saveBatch(WorkOrderDTO workOrderDTO, UserEntity user) {

        String template = "您参与的项目：%s\n%s【%s】通知您，请开始施工";
        List<MessageEntity> messageEntities = workOrderDTO.getUsers().stream().map(userDTO -> {
            MessageEntity message = new MessageEntity();
            String content = String.format(
                    template,
                    workOrderDTO.getProjectName(),
                    userDTO.getUsername(),
                    ProjectRole.get(userDTO.getUserrole()).getDescription()
            );
            message.setMsgType(Msg.NOTICE.getValue());
            message.setType(MsgType.WORK_ORDER.getValue());

            message.setTitle(MsgType.WORK_ORDER.getMsg());
            message.setKeyIds(workOrderDTO.getProjectId());
            message.setContent(content);
            message.setUserId(userDTO.getId());
            message.setAdminUserId(user.getId());
            message.setAdminUserName(user.getUsername());
            return message;
        }).collect(Collectors.toList());
        this.insertBatch(messageEntities);
    }

    @Override
    public long selectCount(Long userId) {
        return baseDao.selectCount(new LambdaQueryWrapper<MessageEntity>()
                .eq(MessageEntity::getUserId, userId)
                .eq(MessageEntity::getIsRead, 0)
        );
    }

    @Override
    public int countUnRead(Long userId) {
        return baseDao.countUnRead(userId);
    }

    @Override
    public List<MessageEntity> selectUnRead(Long userId) {
        return baseDao.selectUnRead(userId);
    }

    @Override
    public int readAll(Long userId, Integer read) {
        return baseDao.readAll(userId, read);
    }

    @Override
    public void read(Long[] msgIds, int isRead) {
        UpdateWrapper<MessageEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", Arrays.stream(msgIds).collect(Collectors.toList()));
        MessageEntity msg = new MessageEntity();
        msg.setIsRead(isRead);
        baseDao.update(msg, updateWrapper);
    }

    @Override
    public PageData<MessageDTO> page(Map<String, Object> params) {
        IPage<MessageEntity> page = getPage(params, null, false);
        List<MessageEntity> list = baseDao.getList(params);
        return getPageData(list, page.getTotal(), MessageDTO.class);
    }
}